import { HvigorNode, HvigorPlugin } from "@ohos/hvigor";
import { OhosHapContext, OhosPluginId, Target } from "@ohos/hvigor-ohos-plugin";
import { RouterHapGeneratorTask } from "./tasks/RouterHapGeneratorTask";
import { CleanTask } from "./tasks/CleanTask";
import { CopyRouterMapTask } from "./tasks/CopyRouterMapTask";
import { Logger } from "./utils/Logger";
import GeneratorStore from "./tasks/GeneratorStore";
import { Hvigor } from "@ohos/hvigor/src/base/external/core/hvigor";

export function RouterAppPlugin(hvigor: Hvigor): HvigorPlugin {
  return {
    pluginId: "RouterAppPlugin",
    apply: async (node) => {
      hvigor.nodesEvaluated(() => {
        Logger.info("RouterAppPlugin nodesEvaluated exec");
        registerRouterGeneratorTask(node);
      });
      hvigor.buildFinished(() => {
        Logger.info("RouterAppPlugin buildFinished exec");
        GeneratorStore.deleteAll();
      });
    },
  };
}

function registerRouterGeneratorTask(node: HvigorNode) {
  const hapContext = node.getContext(
    OhosPluginId.OHOS_HAP_PLUGIN
  ) as OhosHapContext;
  hapContext?.targets((target: Target) => {
    node.registerTask(CleanTask(node));
    node.registerTask(RouterHapGeneratorTask(target, node));
    node.registerTask(CopyRouterMapTask(target, node));
  });
}
